// const app = require('express')()

//导入数据库操作模块
const db = require("../../db/index.js")

// 格式化时间
var moment = require('moment')



/**
 * 获取学生列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getStudentList = (req, res) => {

    let sql = ''
    let department = req.query.department
    let name = req.query.name
    let size = parseInt(req.query.limit)
    let start = (parseInt(req.query.page) - 1) * size
    let sqlArr = []
    if (!name || name == "") {
        if (!department || department == "" || department + "" == "全部") {
            sql = `SELECT COUNT(*) FROM xks_student WHERE status != 0;
            SELECT * FROM xks_student WHERE status != 0 limit ?,?`;
            sqlArr = [start, size]
        }
        else {
            sql = `SELECT COUNT(*) FROM xks_student  WHERE status != 0 AND department = ?;
            SELECT * FROM xks_student  WHERE status != 0 AND department = ? limit ?,?`;
            sqlArr = [department, department, start, size]
        }

        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    videos: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    } else {
        if (!department || department == "" || department == "全部") {
            sql = `SELECT COUNT(*) FROM xks_student  WHERE status != 0 AND name LIKE concat('%',?, '%');
            SELECT * FROM xks_student  WHERE status != 0 AND name LIKE concat('%',?, '%') limit ?,?`;
            sqlArr = [name, name, start, size]
        } else {
            sql = `SELECT COUNT(*) FROM xks_student  WHERE status != 0 AND name LIKE concat('%',?, '%') AND department = ?;
            SELECT * FROM xks_student  WHERE status != 0 AND name LIKE concat('%',?, '%') AND department = ? limit ?,?`;
            sqlArr = [name, department, name, department, start, size]
        }
        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    videos: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    }
}

/**
 * 增加学生
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.addStudent = (req, res) => {

    const Student_info = req.body;
    if (JSON.stringify(Student_info) == "{}") {
        console.log('【增加学生发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Student_info.name || !Student_info.phone || !Student_info.major || Student_info.sex) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    //创建时间
    let nowTime = new Date()
    var formatTime = moment(nowTime).format('YYYY-MM-DD HH:mm')
    Student_info['create_time'] = formatTime;

    const addSql = `INSERT INTO xks_student SET ? `
    db.query(addSql, Student_info, (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '增加失败，请稍后再试！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '增加成功',
            data: result.affectedRows
        })
    })

}


/**
 * 删除学生
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.delStudent = (req, res) => {

    const Student_info = req.query;
    if (JSON.stringify(Student_info) == "{}") {
        console.log('【删除学生发送错误】' + 'req.body ===> ', req.query)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Student_info.id) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }
    const delSql = `UPDATE xks_student SET status = 0 WHERE id = ?`
    db.query(delSql, Student_info.id, (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '删除失败，请检查ID是否有误！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '删除成功！',
            data: {}
        })
    })

}


/**
 * 更新学生
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.updateStudent = (req, res) => {

    const Student_info = req.body;
    if (JSON.stringify(Student_info) == "{}") {
        console.log('【更新学生发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Student_info.id || !Student_info.phone || !Student_info.name) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }
    const id = Student_info.id

    delete Student_info.id
    const updateSql = `UPDATE xks_student SET ?  WHERE status != 0 AND id = ?`
    db.query(updateSql, [Student_info, id], (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '更新失败，请稍后再试！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '更新成功',
            data: result.affectedRows
        })
    })
}